from PySide2.QtCore import *
from PySide2.QtGui import *
from PySide2.QtWidgets import *

from pandas import DataFrame

from common.pd import get_tb_data
from common.pyside2_table.qtable import Base_Table
from common.pyside2_table.qt_wgt import show_msg
from common.config import public_data
from api.api_project import get_contract_by_lot_code
from view.common_fun import add_download_widget
from view.tab_widget import Header_Select_Layout, Header_search_Layout
from view.table_col_list import doc_e_col_model_list


class View_Doc_E(QWidget):
    def __init__(self):
        super().__init__()
        self.view_name = "tab_doc_e"
        self.data = public_data
        self.db_table_name = "doc_e"

        self.setupUi()
        self.bind()

    def setupUi(self):
        # region 布局
        # 整体布局为垂直布局
        lt_pg = QVBoxLayout(self)
        fm_ctrl = QFrame()

        lt_pg.addWidget(fm_ctrl)
        lt_header = QHBoxLayout(fm_ctrl)

        # endregion

        # region 项目、制造厂及采购包选择
        self.lt_select = Header_Select_Layout(lt_header, self.cmb_change)
        self.lt_select.lb_factory.setHidden(True)
        self.lt_select.cmb_factory.setHidden(True)

        # 左侧项目cmb
        left_spacer = QSpacerItem(120, 20, QSizePolicy.Fixed, QSizePolicy.Minimum)
        lt_header.addItem(left_spacer)

        # endregion

        # region 中间查询
        self.search_txt_ly = Header_search_Layout(lt_header)
        self.btn_once_search = QPushButton("once搜索")
        lt_header.addWidget(self.btn_once_search)
        # endregion

        # region 信息展示标签和表格
        self.lb_message = QLabel(text="文件更新日期是：")
        self.lb_message.setAutoFillBackground(False)
        self.lb_message.setWordWrap(True)
        lt_pg.addWidget(self.lb_message, 0, Qt.AlignLeft)

        # 数据表
        self.tb_doc_e = Base_Table("doc_e", doc_e_col_model_list)
        self.tb_doc_e.horizontalHeader().setSectionResizeMode(QHeaderView.ResizeToContents)
        self.tb_doc_e.setSelectionBehavior(QAbstractItemView.SelectRows)  # 设置为行模式
        self.tb_doc_e.setSelectionMode(QAbstractItemView.ExtendedSelection)  # 允许选择多个
        lt_pg.addWidget(self.tb_doc_e)
        self.tb_doc_e.reset_data()

        add_download_widget(lt_header, self.tb_doc_e, "doc_e")

        # endregion

    def bind(self):
        self.search_txt_ly.btn_db_search.clicked.connect(self.search_local)

    def update_doc_view(self, condition):
        show_msg(f"已完成查询，共查新{2}条", "blue", self.lb_message)

    def cmb_change(self):
        sql_str = self.get_cmb_sql_str()
        datas = get_tb_data(self.db_table_name, sql_str)
        self.tb_doc_e.reset_data(datas)

    def get_cmb_sql_str(self):
        select_status: dict = self.lt_select.get_change_status()
        cmd_keys = select_status.keys()
        project = ""
        lot_code = ""
        if "project" in cmd_keys:
            project = select_status["project"]
        if "lot_code" in cmd_keys:
            lot_code = select_status["lot_code"]
        sql_str = ""
        if lot_code:
            df: DataFrame = get_contract_by_lot_code(lot_code)
            if project:
                df_channel_code: DataFrame = df[(df['project'] == project) & (df['lot_code'] == lot_code)][
                    "channel_code"]
                channel_codes = df_channel_code.values.tolist()
                if channel_codes:
                    channel_code = channel_codes[0]
                    sql_str = f"channel like '%{project}%{channel_code}%'"
                    return sql_str
            else:
                channel_code_list = df[df['lot_code'] == lot_code]["channel_code"].unique().tolist()
                channel_str_list = []
                for channel_code in channel_code_list:
                    channel_str_list.append(f" channel like '%{channel_code}%' ")

                return " or ".join(channel_str_list)
        if project:
            sql_str = f"channel like '%{project}%'"
            return sql_str

    def search_local(self):
        txt_search_str = self.search_txt_ly.get_search_txt_to_sql()
        if not txt_search_str:
            return
        datas = self.tb_doc_e.datas
        row_count, col_count = datas.shape

        if row_count < 500:
            re_condition_str = ".*" + txt_search_str.replace("*", ".*") + ".*"
            df_find_data = datas[datas['look_up_str'].str.match(re_condition_str)]
            self.tb_doc_e.show_data(df_find_data)
        else:
            txt_condition = "look_up_str like " + "'%" + txt_search_str.replace("*", "%") + "%'"
            cmd_sql_str = self.get_cmb_sql_str()
            if cmd_sql_str:
                sql_str = f'({cmd_sql_str})' + " and " + f'({txt_condition})'
            else:
                sql_str = txt_condition

            datas = get_tb_data(self.db_table_name, sql_str)
            self.tb_doc_e.reset_data(datas)
